package com.example.demo.Task;

import com.example.demo.domain.dto.ClassInfo;
import com.example.demo.domain.result.helper.Course;
import com.example.demo.domain.send.DingMessage;
import com.example.demo.service.ScheduleService;
import com.example.demo.service.SendDingMessageService;
import com.example.demo.utils.ParseUtil;
import com.google.gson.Gson;
import java.util.Arrays;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;

/**
 * 自动爬取课表信息并存储至数据库
 *
 * @author lizijian
 */
@Data
@Slf4j
public class GetClassScheduleThread implements Runnable {

    private ScheduleService scheduleService;
    private static Gson json = new Gson();
    private ClassInfo classInfo;

    public GetClassScheduleThread(ScheduleService scheduleService, ClassInfo classInfo) {
        this.scheduleService = scheduleService;
        this.classInfo = classInfo;
    }

    @Override
    public void run() {
        try {
            log.info(classInfo.getClassName() + ":爬取开始");
            ArrayList<Course> courses = ParseUtil.getClassSchedule(classInfo.getClassName());
            String jsonData = null;
            if (courses.size() > 0) {
                jsonData = json.toJson(courses);
            }
            scheduleService.insertSchedule(classInfo.getCollegeName(), classInfo.getGrade(), classInfo.getClassName(), jsonData);
            log.info(classInfo.getClassName() + " 爬取结束");
            if ("19软件3".equals(classInfo.getClassName())) {
                scheduleService.insertSchedule("示例学院", "19", "示例班级", jsonData);
            }
        }catch (Exception e){
            log.error(classInfo.getClassName()+"-getClassSchedule error");
            log.error("error message:"+e.getMessage());
            log.error("stack:"+ Arrays.toString(e.getStackTrace()));
            SendDingMessageService.sendGetDataMessage(new DingMessage("爬取"+classInfo.getClassName()+"课表失败,errorMessage:"+e.getMessage()));
        }
    }

}
